<template>
  <div class='detail' v-if="detail">
    <!-- 主图轮播 -->
    <van-swipe :autoplay="3000">
      <van-swipe-item v-for="photo in detail.photo" :key="photo.id">
        <img v-lazy="photo.url" :style="{width: '100%'}"/>
      </van-swipe-item>
    </van-swipe>
    <!-- 标题 -->
    <div class="van-multi-ellipsis--l2">
      {{detail.title}}
    </div>
    <!-- 价格 -->
    <div>{{ detail.price | money}}</div>

    <van-divider>图文详情</van-divider>

    <img
      v-for="desc in detail.descContentList"
      :key="desc.image.id"
      v-lazy="desc.image.url"
      :style="{width: '100%', display: 'block'}"
      alt="">

    <!-- 商品导航 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" dot />
      <van-goods-action-icon
        icon="cart-o"
        text="购物车"
        :badge="totalAmount"
        to="/cart"
      />
      <van-goods-action-icon icon="shop-o" text="店铺" badge="12" />
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        @click="handleAddToCart"
      />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import { getDetail } from '@/api/detail'
export default {
  name: 'Detail',
  data() {
    return {
      detail: null,
    }
  },
  computed: {
    totalAmount() {
      return this.$store.getters.totalAmount
    },
  },
  created() {
    const { id } = this.$route.params
    // 根据 id 查询商品详情
    getDetail(id)
      .then(data => {
        console.log('商品详情：', data)
        this.detail = data.detail
      })
      .catch(console.log)
  },
  methods: {
    handleAddToCart() {
      // 构建当前选购的商品对象
      const { id, image, title, price } = this.detail
      const current = {
        id,
        title,
        image,
        price,
        amount: 1,
      }
      // 修改 store 中的购物车状态数据
      this.$store.commit('addToCart', current)
      // 提示加入购物车成功
      this.$toast({
        type: 'success',
        message: '加入成功',
        duration: 1000,
      })
    },
  },
}
</script>

<style lang='less' scoped>

</style>
